package com.zuoban.service.strategy;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpStatus;
import com.zuoban.anno.LoginEnum;
import com.zuoban.anno.LoginStrategy;
import com.zuoban.common.Result;
import com.zuoban.dto.UserInfoDto;
import com.zuoban.dto.UserLoginDto;
import com.zuoban.entity.sys.SysLog;
import com.zuoban.log.Subject;
import com.zuoban.mapper.BaseUserInfoMapper;
import com.zuoban.util.JwtUtil;
import com.zuoban.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @BelongsProject: zuoban-boot
 * @BelongsPackage: com.zuoban.service.strategy
 * @Author: zxy
 * @CreateTime: 2022-10-10
 * @Description: ...
 */
@RequiredArgsConstructor
@LoginStrategy(name = LoginEnum.ACCOUNT)
@Component(value = "account")
public class AccountLoginImpl implements LoginStrategyService {

    private final RedisUtil redisUtil;
    private final BaseUserInfoMapper baseUserInfoMapper;
    private final JwtUtil jwtUtil;
    private final Subject subject;

    @Override
    public Result doLogin(HttpServletRequest request, UserLoginDto userLoginDto) {
        Result result;
        String code = (String) redisUtil.get("ImgCode|"+userLoginDto.getUserAccount());
        if (!userLoginDto.getCode().equals(code)){
            result = new Result(HttpStatus.HTTP_NO_CONTENT,"验证码不正确，请重新输入",null);
        }else {
            userLoginDto.setUserPwd(SecureUtil.md5(userLoginDto.getUserPwd()));
            UserInfoDto userInfoDto = baseUserInfoMapper.findByUserAccount(userLoginDto);
            if (userInfoDto == null){
                result = new Result(com.zuoban.constant.HttpStatus.HTTP_NOT_FOUND,"用户名或密码不正确，请检查后再登录",null);
            }else {
                HashMap<String, String> tokenMap = new HashMap<>();
                tokenMap.put("userId",String.valueOf(userInfoDto.getUserId()));
                String token = jwtUtil.createToken(tokenMap);
                // 更新token
                baseUserInfoMapper.updateToken(userInfoDto.getUserId(),token);
                redisUtil.set("token|"+ userInfoDto.getUserId(),token,3600*24*15);
                userInfoDto.setToken(token);
                result = Result.success(userInfoDto);
                // 日志埋点 内部是异步 不用担心阻塞
                subject.notifyObserver(request,null,new SysLog(userInfoDto.getUserId(),userInfoDto.getUserAccount()+" 选择了账户登录！"));
            }

        }
        return result;
    }
}
